#include <sstream>
#include "userbuffer.h"

UserBuffer::UserBuffer(void)
{
	clear();
}
void UserBuffer::clear(void)
{
	length = 0;
	memset(data, 0, sizeof(data));
}
void UserBuffer::push_back(uint8_t c)
{
	if(length == 0xffff)
	{
		memmove(data, data+1, length-1);
		length--;
	}
	data[length++] = c;
}
void UserBuffer::pop_front(void)
{
	if(length > 0)
	{
		memmove(data, data+1, length-1);
		length--;
	}
}

bool UserBuffer::check(void)
{
	if(length < sizeof(GB3761_Header))
	{
		return false;
	}
	if(header().checkHeader() == false)
	{
		pop_front();
		return false;
	}
	if(length < sizeof(GB3761_Header) + header().getLength() + 2)
	{
		return false;
	}
	uint8_t cs = 0;
	uint16_t l = header().getLength();
	uint8_t *p = data + sizeof(GB3761_Header);
	for(int i = 0; i < l; i++)
	{
		cs += p[i];
	}
	if(cs != p[l] || 0x16 != p[l+1])
	{
		pop_front();
		return false;
	}
	return true;
}
bool UserBuffer::packup(void)
{
	eMtErr err = emtPack(&m_data, &length, data);
	if(err != MT_OK)
	{
		printf("emtPack.err=%d, %s\n", err, smtGetErr(err));
		return false;
	}
	return true;
}
bool UserBuffer::unpack(void)
{
	eMtErr err = emtUnPack(&m_data, data, length);
	if(err != MT_OK)
	{
		printf("emtPack.err=%d, %s\n", err, smtGetErr(err));
		return false;
	}
	return true;
}
GB3761_Header& UserBuffer::header(void)
{
	return *(GB3761_Header*)data;
}

string UserBuffer::toStringF(void)const
{
	string s;
	for(int i = 0; i < length; i++)
	{
		char buf[32];
		snprintf(buf, sizeof(buf), "%02X ", data[i]);
		s += buf;
	}
	return s;
}

string UserBuffer::toStringU(void)const
{
	stringstream s;
	s << "A1="	<< hex << getRegion()	<< " "; 
	s << "A2="	<< dec << getTerminal()		<< " "; 
	s << "A3="	<< getMac()		<< " "; 
	s << "T="	<< getTeam()	<< " "; 
	s << "DIR="	<< getDir()		<< " "; 
	s << "PRM="	<< getPrm()		<< " "; 
	s << "AFN="	<< getAfn()		<< " "; 
	s << "Tpv="	<< getTpv()		<< " "; 
	s << "POS="	<< getPos()		<< " "; 
	s << "CON="	<< getCon()		<< " "; 
	s << "SEQ="	<< getSeq()		<< " "; 
	s << "APP="	<< getApp()		<< " "; 
	for(int i = 0; i < getNum(); i++)
	{
		s << "Pn[" << i << "]="	<< getPn(i)	<< " "; 
		s << "Fn[" << i << "]="	<< getFn(i)	<< " "; 
	}
	return s.str();
}

